#include "parse_thread.h"
#include <QDebug>
#include <QFile>

#define BUFFER_LEN 8192
ParseThread::ParseThread(QObject *parent) : QThread(parent)
{

}
ParseThread::~ParseThread()
{
    m_stop = 1;
    m_waitCondition.wakeOne();
    quit();
    wait();
    m_stop = 1;
}
void ParseThread::recvData(QByteArray data)
{
    m_mutex.lock();
    m_dataQueue.append(data);
    m_waitCondition.wakeOne();
    m_mutex.unlock();
}

void ParseThread::run()
{
    m_stop = 0;
    m_dataQueue.clear();
    QByteArray data;
    while(1){
        QMutexLocker lock(&m_mutex);
        if(m_dataQueue.isEmpty()){
            m_waitCondition.wait(&m_mutex);
        }else{
            data = m_dataQueue.takeFirst();
            lock.unlock();
            //解析
            handleData(data);
        }
        if(m_stop)
            break;
    }
}

void ParseThread::handleData(QByteArray &data)
{
    while(!data.isEmpty()){
        PackageBody body;
#ifdef Normal
        auto header = data.mid(0,4);
        int len = data.at(4) | data.at(5)<< 8 | data.at(6) << 16 | data.at(7) << 24;
        auto type = data.at(8) | data.at(9)<< 8 | data.at(10) << 16 | data.at(11) << 24;
        qDebug()<<"len = "<<len<<"type = "<<type;
        memcpy(&body,data.data(),len);
        data.remove(0,len);
#else
        PackageHeader header;

        memcpy(&header,data.data(),sizeof (PackageHeader));
        qDebug()<<"len = "<<header.lengthOfFrame<<"type = "<<header.typeOfFrame;
        memcpy(&body,data.data(),header.lengthOfFrame);

        signRecvPhotoInfo();

        data.remove(0,header.lengthOfFrame);
#endif
        //do something.........
        handleParseImageData(body);
    }
}
void ParseThread::handleParseImageData(PackageBody &data)
{
    qDebug()<<"test 1 = "<<data.test1<<" test 2 = "<<data.test2<<" test 3 = "<<data.test3;
}
